<?php
/**
 * api模块的基类控制器
 */
namespace Api\Controller;
use \Think\Controller;
use Api\Library\ErrorCode;
use Api\Library\ErrorMsg;
use Api\Library\Helper;

class ApiController extends Controller
{
    private $uid;
    protected static $server;

    /**
     * 初始化
     */
    protected function _initialize()
    {
        self::$server = C('SERVER');
        Helper::$ajax = $this->getAjax();
        Helper::$param = ['code' => ErrorCode::SuccessCode];
        if(IS_AJAX){
            $key = Helper::$ajax['key'];
            if(C('RECEPT_KEY') !== $key){
                $this->ajaxReturn(['code'=>ErrorCode::InvalidAuthKey, 'msg' => ErrorMsg::InvalidAuthKey]);
            }
        }
    }

    private function getAjax()
    {
        $json = file_get_contents("php://input");
        return json_decode($json, 1);
    }

    /**
     * 设置uid
     */
    protected function setUid($uid)
    {
        $this->uid = $uid;
    }

    /**
     * 获取uid
     */
    protected function getUid()
    {
        return $this->uid;
    }

    /**
     * 数据签名认证
     */
    protected function data_auth_sign($data) {
        if (!is_array($data)) {
            $data = (array)$data;
        }

        ksort($data);
        $code = http_build_query($data);
        $sign = sha1($code);

        return $sign;
    }

    /**
     * 检测用户是否登录
     */
    public function is_login() {
        $sessionName = 'user_auth::' . session('uid');
        $signName = 'user_auth_sign::' . session('uid');
        $user = session($sessionName);
        if (empty($user)) {
            return 0;
        } else {
            if (session($signName) == $this->data_auth_sign($user)) {
                $this->setUid($user['uid']);
                return $user['uid'];
            } else {
                return 0;
            }
        }
    }
}